package com.eric.code.oauth2.api;

import com.eric.code.oauth2.model.App;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * Created by eric on 17-3-26.
 */
public class OauthService {
    public static final String CACHED_NAME = "oauth2Cached";
    public static final String AUTH_CODE="auth_code";
    public static final String ACCESS_TOKEN="assess_token";

    public static final OauthService me = new OauthService();
    private App dao = new App().dao();

    public boolean checkClientId(String clientId){
        App app = dao.findFirst("select * from oauth2_client where client_id=?",clientId);
        return app != null;
    }

    public App findByClientId(String clientId){
        return dao.findFirst("select * from oauth2_client where client_id=?",clientId);
    }

    public void setAuthCode(String authCode, long userId){
        CacheKit.put(CACHED_NAME,authCode,userId);
    }

    public void setAccessToken(String accessToken,long userId){
        CacheKit.put(CACHED_NAME,accessToken,userId);
    }

    public boolean checkAuthCode(String authCode){
        return CacheKit.get(CACHED_NAME,authCode) != null;
    }

    public boolean checkAccessToken(String accessToken){
        return CacheKit.get(CACHED_NAME,accessToken) != null;
    }

    public long getUserIdByAccessToken(String accessToken){
        return CacheKit.get(CACHED_NAME,accessToken);
    }
    public long getUserIdByCode(String code){
        return CacheKit.get(CACHED_NAME,code);
    }
    /**
     * 认证的有效时间
     * @return
     */
    public long getExpireIn() {
        return 3600L;
    }
}
